package com.lefeng.cockpit.admin.interceptor;

import com.lefeng.cockpit.common.config.UserLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 Cookie 中获取用户信息
        Cookie[] cookies = request.getCookies();
        String userName = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("X-SSO-USER".equals(cookie.getName())) {
                    userName = cookie.getValue();
                    break;
                }
            }
        }
        UserLocal.setUser(userName);
        return true;
    }

    /**
     * 在请求处理完成后，视图渲染完成后调用。
     *
     * 主要用于资源清理和异常处理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserLocal.removeUser();
    }

    /**
     * 在控制器处理请求之后，但在视图渲染之前调用。
     *
     * 用于处理模型和视图的相关工作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}

